# -*- coding: utf-8 -*-
"""
云存储文件管理API控制器
@api-version: 1.0.0
// REF: API-CLOUD-FILES-010
"""

import json
import requests
from datetime import datetime
from flask import Blueprint, request, jsonify, current_app, redirect, Response
from werkzeug.utils import secure_filename

from backend.models import db
from backend.models.cloud_storage_account import CloudStorageAccount
from backend.clouds_sdk.cloud_factory import CloudFactory
from backend.clouds_sdk.client_cache_manager import get_cache_manager
from backend.utils.api_response import ApiResponse
from backend.utils.auth import login_required, get_current_user
from backend.utils.validators import validate_json

# 创建蓝图
cloud_files_bp = Blueprint('cloud_files', __name__, url_prefix='/cloud-files')

def _get_cached_client(user_id, account, auto_login=True):
    """获取缓存的云存储客户端
    
    智能登录检测逻辑：
    1. 优先使用token进行登录状态检测
    2. 如果token有效且已登录，直接使用缓存的客户端
    3. 如果token无效或未登录，使用密码登录
    4. 密码登录成功后，获取并保存新的token信息到数据库
    
    Args:
        user_id: 用户ID
        account: CloudStorageAccount实例
        auto_login: 是否在token无效时自动登录，默认为True
        
    Returns:
        tuple: (client, error_response) - 成功时error_response为None
    """
    try:
        # 准备账号信息
        account_info = {
            'id': account.id,
            'cloud_provider': account.cloud_provider,
            'cloud_account': account.cloud_account,
            'cloud_password': account.cloud_password,
            'token_info': account.get_token_info() if hasattr(account, 'get_token_info') else None
        }
        
        current_app.logger.debug(f"开始获取缓存客户端: account_id={account.id}, user_id={user_id}")
        
        # 从缓存管理器获取客户端
        cache_manager = get_cache_manager()
        client = cache_manager.get_client(user_id, account_info, auto_login=auto_login)
        
        if not client:
            current_app.logger.error(f"缓存管理器返回空客户端: account_id={account.id}")
            return None, ApiResponse.error("获取云存储客户端失败", code=500).to_response()
        
        # 检查是否有新的token信息需要更新到数据库
        new_token_info = account_info.get('new_token_info')
        if new_token_info and hasattr(account, 'set_token_info'):
            try:
                current_token = account.get_token_info() if hasattr(account, 'get_token_info') else None
                # 只有当token发生变化时才更新数据库
                if current_token != new_token_info:
                    current_app.logger.info(f"检测到新token信息，开始更新数据库: account_id={account.id}")
                    account.set_token_info(new_token_info)
                    db.session.commit()
                    current_app.logger.info(f"成功更新账号 {account.id} 的token信息")
                else:
                    current_app.logger.debug(f"Token信息未变化，无需更新: account_id={account.id}")
            except Exception as e:
                current_app.logger.error(f"更新token信息失败: account_id={account.id}, error={e}")
                db.session.rollback()
                # token更新失败不影响客户端使用，继续返回客户端
        
        # 验证客户端登录状态
        if not client.check_login_status():
            current_app.logger.warning(f"客户端登录状态无效: account_id={account.id}")
            return None, ApiResponse.error("云存储客户端登录状态无效", code=401).to_response()
        
        current_app.logger.debug(f"成功获取缓存客户端: account_id={account.id}")
        return client, None
        
    except Exception as e:
        current_app.logger.error(f"获取缓存客户端失败: account_id={account.id if account else 'None'}, error={str(e)}")
        return None, ApiResponse.error(f"获取云存储客户端失败: {str(e)}", code=500).to_response()


def _create_authenticated_client(account, auto_login=True):
    """创建已认证的云存储客户端（兼容性函数）
    
    Args:
        account: CloudStorageAccount实例
        auto_login: 是否在token无效时自动登录，默认为True
        
    Returns:
        tuple: (client, error_response) - 成功时error_response为None
    """
    # 获取当前用户ID
    try:
        user = get_current_user()
        user_id = user.id if user else 0
        return _get_cached_client(user_id, account, auto_login)
    except Exception as e:
        current_app.logger.error(f"获取当前用户失败: {str(e)}")
        return None, ApiResponse.error(f"获取当前用户失败: {str(e)}", code=500).to_response()

@cloud_files_bp.route('/files', methods=['GET'])
@login_required
def list_files():
    """获取云存储文件列表
    // REF: API-CLOUD-FILES-001
    """
    current_app.logger.info(f"[DEBUG] list_files函数被调用")
    try:
        user = get_current_user()
        current_app.logger.info(f"[DEBUG] 获取到用户: {user.id if user else 'None'}")
        
        # 获取参数
        account_id = request.args.get('accountId', type=int)
        current_app.logger.info(f"[DEBUG] 获取参数 account_id: {account_id}")
        folder_id = request.args.get('folderId')
        parent_path = request.args.get('parentPath', '/')
        page = request.args.get('pageNum', 1, type=int)  # 修正参数名
        page_size = request.args.get('pageSize', 20, type=int)
        folders_only = request.args.get('foldersOnly', 'false').lower() == 'true'
        auto_login = request.args.get('autoLogin', 'true').lower() == 'true'
        
        # 优先使用folderId，如果没有则使用parentPath
        if folder_id is not None:
            parent_path = folder_id if folder_id else '/'
        
        current_app.logger.info(f"[DEBUG] 最终使用的folder_id/parent_path: {parent_path}")
        
        if not account_id:
            current_app.logger.error(f"[DEBUG] 账号ID为空")
            return ApiResponse.error("账号ID不能为空", code=400).to_response()
        
        # 验证账号权限（支持用户私有账号和公共账号）
        current_app.logger.info(f"[DEBUG] 查询账号: account_id={account_id}, user_id={user.id}")
        account = CloudStorageAccount.query.filter(
            CloudStorageAccount.id == account_id,
            (CloudStorageAccount.user_id == user.id) | (CloudStorageAccount.user_id.is_(None))
        ).first()
        
        if not account:
            current_app.logger.error(f"[DEBUG] 云存储账号不存在: account_id={account_id}, user_id={user.id}")
            return ApiResponse.error("云存储账号不存在", code=404).to_response()
        
        current_app.logger.info(f"[DEBUG] 找到账号: {account.cloud_account} (用户ID: {account.user_id})")
        
        # 使用缓存管理器获取客户端
        client, error_response = _get_cached_client(user.id, account, auto_login=auto_login)
        if error_response:
            return error_response
        
        # 获取标准化格式的文件列表
        standardized_files = client.get_files_standardized(
            folder_id=None if parent_path == '/' else parent_path,
            page_num=page,
            page_size=page_size
        )
        
        if standardized_files is None:
            return ApiResponse.error("获取文件列表失败", code=500).to_response()
        
        # 转换为字典格式
        files_data = [file_info.to_dict() for file_info in standardized_files]
        
        return ApiResponse.success({
            'files': files_data,
            'total': len(files_data),
            'page': page,
            'pageSize': page_size,
            'parentPath': parent_path,
            'accountInfo': {
                'id': account.id,
                'name': account.cloud_account,
                'cloudType': account.cloud_provider
            }
        }).to_response()
        
    except Exception as e:
        current_app.logger.error(f"获取云存储文件列表失败: {str(e)}")
        return ApiResponse.error(f"获取文件列表失败: {str(e)}", code=500).to_response()

@cloud_files_bp.route('/folders', methods=['POST'])
@login_required
@validate_json(['accountId', 'name'])
def create_folder(data):
    """创建文件夹
    // REF: API-CLOUD-FILES-002
    """
    try:
        user = get_current_user()
        
        account_id = data.get('accountId')
        folder_name = data.get('name', '').strip()
        parent_folder_id = data.get('parentPath', '') or data.get('parentFolderId', '')
        
        if not folder_name:
            return ApiResponse.error("文件夹名称不能为空", code=400).to_response()
        
        # 验证账号权限（支持用户私有账号和公共账号）
        account = CloudStorageAccount.query.filter(
            CloudStorageAccount.id == account_id,
            (CloudStorageAccount.user_id == user.id) | (CloudStorageAccount.user_id.is_(None))
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在", code=404).to_response()
        
        # 检查账号状态
        if not account.is_online:
            return ApiResponse.error("账号未在线，无法创建文件夹", code=400).to_response()
        
        # 使用缓存管理器获取客户端
        client, error_response = _get_cached_client(user.id, account)
        if error_response:
            return error_response
        
        # 创建文件夹 - 使用base_client.py中定义的参数顺序
        result = client.create_folder(
            parent_id=parent_folder_id,
            folder_name=folder_name
        )
        
        if result:
            current_app.logger.info(f"文件夹创建成功: account_id={account_id}, folder_name={folder_name}, parent_id={parent_folder_id}")
            return ApiResponse.success({
                'message': '文件夹创建成功',
                'folder_name': folder_name,
                'parent_folder_id': parent_folder_id,
                'folder_id': result
            }).to_response()
        else:
            current_app.logger.error(f"文件夹创建失败: account_id={account_id}, folder_name={folder_name}")
            return ApiResponse.error("文件夹创建失败", code=500).to_response()
        
    except Exception as e:
        current_app.logger.error(f"创建文件夹失败: {str(e)}")
        return ApiResponse.error(f"创建文件夹失败: {str(e)}", code=500).to_response()

@cloud_files_bp.route('/files/delete', methods=['DELETE'])
@login_required
@validate_json(['accountId', 'paths'])
def delete_files(data):
    """删除文件或文件夹
    // REF: API-CLOUD-FILES-003
    """
    try:
        user = get_current_user()
        
        account_id = data.get('accountId')
        file_paths = data.get('paths', [])
        
        if not isinstance(file_paths, list) or not file_paths:
            return ApiResponse.error("文件路径列表不能为空", code=400).to_response()
        
        # 验证账号权限
        account = CloudStorageAccount.query.filter_by(
            id=account_id, user_id=user.id
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在", code=404).to_response()
        
        # 创建已认证的云存储客户端
        client, error_response = _get_cached_client(user.id, account)
        if error_response:
            return error_response
        
        # 批量删除文件
        success_count = 0
        failed_files = []
        
        for file_path in file_paths:
            try:
                client.delete_file(file_path)
                success_count += 1
            except Exception as e:
                failed_files.append({
                    'path': file_path,
                    'error': str(e)
                })
        
        return ApiResponse.success({
            'successCount': success_count,
            'totalCount': len(file_paths),
            'failedFiles': failed_files,
            'message': f'成功删除 {success_count} 个文件'
        }).to_response()
        
    except Exception as e:
        current_app.logger.error(f"删除文件失败: {str(e)}")
        return ApiResponse.error(f"删除失败: {str(e)}", code=500).to_response()

@cloud_files_bp.route('/files/move', methods=['PUT'])
@login_required
@validate_json(['accountId', 'sourcePath', 'targetPath'])
def move_file(data):
    """移动/重命名文件
    // REF: API-CLOUD-FILES-004
    """
    try:
        user = get_current_user()
        
        account_id = data.get('accountId')
        source_path = data.get('sourcePath')
        target_path = data.get('targetPath')
        
        # 验证账号权限
        account = CloudStorageAccount.query.filter_by(
            id=account_id, user_id=user.id
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在", code=404).to_response()
        
        # 使用缓存管理器获取客户端
        client, error_response = _get_cached_client(user.id, account)
        if error_response:
            return error_response
        
        # 移动文件
        result = client.move_file(
            source_path=source_path,
            target_path=target_path
        )
        
        return ApiResponse.success({
            'result': result,
            'message': '文件移动成功'
        }).to_response()
        
    except Exception as e:
        current_app.logger.error(f"移动文件失败: {str(e)}")
        return ApiResponse.error(f"移动失败: {str(e)}", code=500).to_response()

@cloud_files_bp.route('/files/copy', methods=['POST'])
@login_required
@validate_json(['accountId', 'sourcePath', 'targetPath'])
def copy_file(data):
    """复制文件
    // REF: API-CLOUD-FILES-005
    """
    try:
        user = get_current_user()
        
        account_id = data.get('accountId')
        source_path = data.get('sourcePath')
        target_path = data.get('targetPath')
        
        # 验证账号权限
        account = CloudStorageAccount.query.filter_by(
            id=account_id, user_id=user.id
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在", code=404).to_response()
        
        # 创建已认证的云存储客户端
        client, error_response = _get_cached_client(user.id, account)
        if error_response:
            return error_response
        
        # 复制文件
        result = client.copy_file(
            source_path=source_path,
            target_path=target_path
        )
        
        return ApiResponse.success({
            'result': result,
            'message': '文件复制成功'
        }).to_response()
        
    except Exception as e:
        current_app.logger.error(f"复制文件失败: {str(e)}")
        return ApiResponse.error(f"复制失败: {str(e)}", code=500).to_response()

@cloud_files_bp.route('/upload', methods=['POST'])
@login_required
def upload_file():
    """文件上传
    // REF: API-CLOUD-FILES-006
    """
    try:
        user = get_current_user()
        
        # 验证文件上传
        if 'file' not in request.files:
            return ApiResponse.error("未选择文件", code=400).to_response()
        
        file = request.files['file']
        if file.filename == '':
            return ApiResponse.error("文件名不能为空", code=400).to_response()
        
        # 获取参数
        account_id = request.form.get('accountId', type=int)
        parent_path = request.form.get('parentPath', '/')
        
        if not account_id:
            return ApiResponse.error("账号ID不能为空", code=400).to_response()
        
        # 验证账号权限
        account = CloudStorageAccount.query.filter_by(
            id=account_id, user_id=user.id
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在", code=404).to_response()
        
        # 文件名安全处理
        filename = secure_filename(file.filename)
        if not filename:
            return ApiResponse.error("文件名无效", code=400).to_response()
        
        # 创建已认证的云存储客户端
        client, error_response = _get_cached_client(user.id, account)
        if error_response:
            return error_response
        
        # 上传文件
        result = client.upload_file(
            file_data=file.read(),
            filename=filename,
            parent_path=parent_path
        )
        
        return ApiResponse.success({
            'file': result,
            'message': '文件上传成功'
        }).to_response()
        
    except Exception as e:
        current_app.logger.error(f"文件上传失败: {str(e)}")
        return ApiResponse.error(f"上传失败: {str(e)}", code=500).to_response()

@cloud_files_bp.route('/files/<path:file_path>/info', methods=['GET'])
@login_required
def get_file_info(file_path):
    """获取文件详细信息
    // REF: API-CLOUD-FILES-007
    """
    try:
        user = get_current_user()
        
        account_id = request.args.get('accountId', type=int)
        
        if not account_id:
            return ApiResponse.error("账号ID不能为空", code=400).to_response()
        
        # 验证账号权限
        account = CloudStorageAccount.query.filter_by(
            id=account_id, user_id=user.id
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在", code=404).to_response()
        
        # 创建已认证的云存储客户端
        client, error_response = _get_cached_client(user.id, account)
        if error_response:
            return error_response
        
        # 获取文件信息
        file_info = client.get_file_info(file_path)
        
        return ApiResponse.success(file_info).to_response()
        
    except Exception as e:
        current_app.logger.error(f"获取文件信息失败: {str(e)}")
        return ApiResponse.error(f"获取文件信息失败: {str(e)}", code=500).to_response()

@cloud_files_bp.route('/download-url', methods=['POST'])
@login_required
@validate_json(['accountId', 'filePath'])
def get_download_url(data):
    """获取文件下载链接
    // REF: API-CLOUD-FILES-008
    """
    try:
        user = get_current_user()
        
        account_id = data.get('accountId')
        file_path = data.get('filePath')
        
        # 验证账号权限
        account = CloudStorageAccount.query.filter_by(
            id=account_id, user_id=user.id
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在", code=404).to_response()
        
        # 创建已认证的云存储客户端
        client, error_response = _get_cached_client(user.id, account)
        if error_response:
            return error_response
        
        # 获取下载链接
        download_url = client.get_download_url(file_path)
        
        return ApiResponse.success({
            'downloadUrl': download_url,
            'filePath': file_path
        }).to_response()
        
    except Exception as e:
        current_app.logger.error(f"获取下载链接失败: {str(e)}")
        return ApiResponse.error(f"获取下载链接失败: {str(e)}", code=500).to_response()


@cloud_files_bp.route('/download/proxy', methods=['POST'])
@login_required
@validate_json(['accountId', 'filePath'])
def download_file_proxy(data):
    """通过本地代理下载文件
    // REF: API-CLOUD-FILES-009
    """
    try:
        user = get_current_user()
        
        account_id = data.get('accountId')
        file_path = data.get('filePath')
        
        # 验证账号权限
        account = CloudStorageAccount.query.filter_by(
            id=account_id, user_id=user.id
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在", code=404).to_response()
        
        # 创建已认证的云存储客户端
        client, error_response = _get_cached_client(user.id, account)
        if error_response:
            return error_response
        
        # 获取下载链接
        download_url = client.get_download_url(file_path)
        if not download_url:
            return ApiResponse.error("获取下载链接失败", code=500).to_response()
        
        # 通过本地代理下载文件
        try:
            # 发起下载请求
            response = requests.get(download_url, stream=True, timeout=30)
            response.raise_for_status()
            
            # 获取文件名
            filename = file_path.split('/')[-1] if '/' in file_path else file_path
            
            # 获取内容类型
            content_type = response.headers.get('Content-Type', 'application/octet-stream')
            
            # 创建流式响应
            def generate():
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        yield chunk
            
            # 返回文件流
            flask_response = Response(
                generate(),
                headers={
                    'Content-Disposition': f'attachment; filename="{filename}"',
                    'Content-Type': content_type,
                    'Content-Length': response.headers.get('Content-Length', '')
                }
            )
            
            current_app.logger.info(f"代理下载文件成功: {file_path}")
            return flask_response
            
        except requests.RequestException as e:
            current_app.logger.error(f"代理下载文件失败: {str(e)}")
            return ApiResponse.error(f"下载文件失败: {str(e)}", code=500).to_response()
        
    except Exception as e:
        current_app.logger.error(f"代理下载文件失败: {str(e)}")
        return ApiResponse.error(f"下载失败: {str(e)}", code=500).to_response()


@cloud_files_bp.route('/download/redirect', methods=['POST'])
@login_required
@validate_json(['accountId', 'filePath'])
def download_file_redirect(data):
    """通过301重定向下载文件
    // REF: API-CLOUD-FILES-010
    """
    try:
        user = get_current_user()
        
        account_id = data.get('accountId')
        file_path = data.get('filePath')
        
        # 验证账号权限
        account = CloudStorageAccount.query.filter_by(
            id=account_id, user_id=user.id
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在", code=404).to_response()
        
        # 创建已认证的云存储客户端
        client, error_response = _get_cached_client(user.id, account)
        if error_response:
            return error_response
        
        # 获取下载链接
        download_url = client.get_download_url(file_path)
        if not download_url:
            return ApiResponse.error("获取下载链接失败", code=500).to_response()
        
        # 301重定向到真实下载地址
        current_app.logger.info(f"重定向下载文件: {file_path} -> {download_url}")
        return redirect(download_url, code=301)
        
    except Exception as e:
        current_app.logger.error(f"重定向下载文件失败: {str(e)}")
        return ApiResponse.error(f"下载失败: {str(e)}", code=500).to_response()


def _create_client_without_login(account):
    """创建云存储客户端但不强制登录
    
    Args:
        account: CloudStorageAccount实例
        
    Returns:
        tuple: (client, error_response) - 成功时error_response为None
    """
    try:
        # 创建云存储客户端，优先使用token信息
        token_info = account.get_token_info() if hasattr(account, 'get_token_info') else None
        client = CloudFactory.create_client(
            cloud_type=account.cloud_provider,
            account_id=account.id,
            username=account.cloud_account,
            password=account.cloud_password,
            token_info=token_info
        )
        
        return client, None
    except Exception as e:
        current_app.logger.error(f"创建云存储客户端失败: {str(e)}")
        return None, ApiResponse.error(f"创建云存储客户端失败: {str(e)}", code=500).to_response()


@cloud_files_bp.route('/login-status', methods=['GET'])
@login_required
def check_login_status():
    """检查云存储账号登录状态
    // REF: API-CLOUD-FILES-011
    """
    try:
        user = get_current_user()
        
        # 获取参数
        account_id = request.args.get('accountId', type=int)
        
        if not account_id:
            return ApiResponse.error("账号ID不能为空", code=400).to_response()
        
        # 验证账号权限
        account = CloudStorageAccount.query.filter_by(
            id=account_id, user_id=user.id
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在或无权限访问", code=404).to_response()
        
        # 创建客户端但不强制登录
        client, error_response = _create_client_without_login(account)
        if error_response:
            return error_response
        
        # 检查登录状态
        is_logged_in = client.check_login_status()
        
        return ApiResponse.success({
            'accountId': account_id,
            'isLoggedIn': is_logged_in,
            'accountName': account.cloud_account,
            'provider': account.cloud_provider
        }).to_response()
        
    except Exception as e:
        current_app.logger.error(f"检查登录状态失败: {str(e)}")
        return ApiResponse.error(f"检查登录状态失败: {str(e)}", code=500).to_response()


@cloud_files_bp.route('/login', methods=['POST'])
@login_required
def manual_login():
    """手动登录云存储账号
    // REF: API-CLOUD-FILES-012
    """
    try:
        user = get_current_user()
        
        # 获取参数
        data = request.get_json()
        if not data:
            return ApiResponse.error("请求数据不能为空", code=400).to_response()
        
        account_id = data.get('accountId')
        
        if not account_id:
            return ApiResponse.error("账号ID不能为空", code=400).to_response()
        
        # 验证账号权限
        account = CloudStorageAccount.query.filter_by(
            id=account_id, user_id=user.id
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在或无权限访问", code=404).to_response()
        
        # 创建客户端但不强制登录
        client, error_response = _create_client_without_login(account)
        if error_response:
            return error_response
        
        # 尝试登录
        if not client.login():
            return ApiResponse.error("云存储账号登录失败，请检查账号密码", code=401).to_response()
        
        # 登录成功后，保存新的token信息到数据库
        new_token_info = client.get_token_info()
        if new_token_info and hasattr(account, 'set_token_info'):
            account.set_token_info(new_token_info)
            db.session.commit()
        
        return ApiResponse.success({
            'accountId': account_id,
            'message': '登录成功',
            'accountName': account.cloud_account,
            'provider': account.cloud_provider
        }).to_response()
        
    except Exception as e:
        current_app.logger.error(f"手动登录失败: {str(e)}")
        return ApiResponse.error(f"手动登录失败: {str(e)}", code=500).to_response()


@cloud_files_bp.route('/cache/status', methods=['GET'])
@login_required
def get_cache_status():
    """获取客户端缓存状态
    // REF: API-CLOUD-FILES-011
    """
    try:
        cache_manager = get_cache_manager()
        
        # 获取缓存统计信息
        stats = cache_manager.get_cache_stats()
        
        # 获取缓存的客户端信息
        clients_info = cache_manager.get_cached_clients_info()
        
        return ApiResponse.success({
            'stats': stats,
            'clients': clients_info,
            'message': '获取缓存状态成功'
        }).to_response()
        
    except Exception as e:
        current_app.logger.error(f"获取缓存状态失败: {str(e)}")
        return ApiResponse.error(f"获取缓存状态失败: {str(e)}", code=500).to_response()


@cloud_files_bp.route('/cache/clear', methods=['POST'])
@login_required
def clear_cache():
    """清理客户端缓存
    // REF: API-CLOUD-FILES-012
    """
    try:
        user = get_current_user()
        data = request.get_json() or {}
        
        cache_manager = get_cache_manager()
        
        # 获取清理类型
        clear_type = data.get('type', 'user')  # user, account, all
        account_id = data.get('accountId')
        
        if clear_type == 'account' and account_id:
            # 清理指定账号的缓存
            success = cache_manager.invalidate_client(user.id, account_id)
            if success:
                message = f'成功清理账号 {account_id} 的缓存'
            else:
                message = f'账号 {account_id} 的缓存不存在或已清理'
            
        elif clear_type == 'user':
            # 清理当前用户的所有缓存
            count = cache_manager.invalidate_user_clients(user.id)
            message = f'成功清理当前用户的 {count} 个客户端缓存'
            
        elif clear_type == 'all':
            # 清理所有缓存（仅管理员）
            # 这里可以添加管理员权限检查
            count = cache_manager.clear_all_cache()
            message = f'成功清理所有 {count} 个客户端缓存'
            
        else:
            return ApiResponse.error("无效的清理类型", code=400).to_response()
        
        return ApiResponse.success({
            'message': message,
            'clearType': clear_type
        }).to_response()
        
    except Exception as e:
        current_app.logger.error(f"清理缓存失败: {str(e)}")
        return ApiResponse.error(f"清理缓存失败: {str(e)}", code=500).to_response()


@cloud_files_bp.route('/cache/refresh', methods=['POST'])
@login_required
@validate_json(['accountId'])
def refresh_client_cache(data):
    """刷新指定账号的客户端缓存
    // REF: API-CLOUD-FILES-013
    """
    try:
        user = get_current_user()
        account_id = data.get('accountId')
        
        # 验证账号权限
        account = CloudStorageAccount.query.filter_by(
            id=account_id, user_id=user.id
        ).first()
        
        if not account:
            return ApiResponse.error("云存储账号不存在", code=404).to_response()
        
        cache_manager = get_cache_manager()
        
        # 先清理旧缓存
        cache_manager.invalidate_client(user.id, account_id)
        
        # 重新获取客户端（这会创建新的缓存）
        client, error_response = _get_cached_client(user.id, account, auto_login=True)
        if error_response:
            return error_response
        
        return ApiResponse.success({
            'accountId': account_id,
            'message': '客户端缓存刷新成功',
            'accountName': account.cloud_account,
            'provider': account.cloud_provider
        }).to_response()
        
    except Exception as e:
        current_app.logger.error(f"刷新客户端缓存失败: {str(e)}")
        return ApiResponse.error(f"刷新客户端缓存失败: {str(e)}", code=500).to_response()